package Controllers;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import entities.NotificationMessage;

import ocsf.server.ConnectionToClient;

import Database.mysqlConnection;
import MessagePacks.MessageNotificationPack;
import MessagePacks.MessagePack;

/**
 *@author Juan Alapin - 324507516
 *@author Giora Yaffe - 036551281
 *@author Shachar Gritzman - 300174026
 *@author Nir Porat - 021515580
*/

public class MessageController {

	private mysqlConnection SqlDB;
	private NotificationMessage notificationMessage;
	
	/**
	 * Constructor
	 * @param DB:mysqlConnection - SQL DataBase
	 */
	public MessageController(mysqlConnection DB){
		this.SqlDB = DB;
	}
	
	/**
	 * Store a message at the DataBase
	 * @param usrID - the user the message belong to
	 * @param processID - the process the message came from
	 * @param type - type of the message
	 * @param msg - the content of the message
	 * @param date - the date the message was sent
	 * @param read - the recipient has read the the message
	 * @return mid - generate ID for the message
	 */
	public int storemsg(int usrID ,int processID,int type ,String msg, String date,Boolean read){
		String addQuery = new String("INSERT INTO `ICM`.`messages`(usrID,processID,type,msg,date,readOk) VALUES (" + usrID + ",'" + processID + "','" + type + "','" + msg + "','" + date + "','" + read+"');");
		//String addQuery = new String("INSERT INTO `ICM`.`messages`(mID,usrID,processID,type,msg,date,readOk)" + " VALUES('','" + usrID +"','" + processID + "','" + type + "','" + msg + ",'" + date + "','" + read + "');");
		int mid = -1;
		try {
			mid = SqlDB.AddAutoInc(addQuery);
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		}
		return mid;	
	}
	
	
	/**
	 * Store message with fewer arguments
	 * @param nMsg:NotificationMessage
	 * @return mid - generate ID for the message
	 */
	public int storemsg(NotificationMessage nMsg){
		//String addQuery = new String("INSERT INTO `ICM`.`messages`(usrID,processID,type,msg,date,readOk) VALUES (" + usrID + ",'" + processID + "','" + type + "','" + msg + "','" + date + "','" + read+"');");
		//String By Juan: String addQuery1 = new String("INSERT INTO `ICM`.`messages`(mID,usrID,processID,type,msg,date,read) VALUES('','" + nMsg.getusrID() +"','" + nMsg.getprocessID() + "','" + nMsg.gettype() + "','" + nMsg.getmsg() + "',CURDATE(),'" + nMsg.getread() + "');");
		//int mid = -1;
		SqlDB.SendMessageInSystem(nMsg);
		return(1);
	}
	
	
	/**
	 * Retrieve the message from the DataBase
	 * @param usrID - the user the message belong to
	 * @param client - enable the connection 
	 * @return 0 if fail , 1 success 
	 */
	public int retrieve(MessageNotificationPack msg, ConnectionToClient client){
		String query = new String("SELECT * FROM `ICM`.`messages` L WHERE L.usrID = '" + msg.getUserID() + "';");
		ResultSet rs = SqlDB.queryDB(query);
		ArrayList <NotificationMessage> msglist = new ArrayList <NotificationMessage> ();
		
		try
		{
			while(rs.next()){
				//int mID, int usrID, int processID, int type, Boolean read
				NotificationMessage notificationMessage = new NotificationMessage(rs.getInt("mID"), rs.getInt("usrID"), rs.getInt("processID"), rs.getInt("type"), rs.getInt("readOk") );
				msglist.add(notificationMessage);
			}
			
			
		}
		catch (SQLException e)
		{
			
		}
		
		MessageNotificationPack pack = new MessageNotificationPack(msglist ,msg.getUserID() );
		try {
			rs.close();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		try {
			client.sendToClient(pack);
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}
	
	/**
	 * This function sends an Email message to client
	 * @param Destination - target email address
	 * @param Msg - the message content
	 * @param title - the message title
	 */
	public void SendMail(String Destination,String Msg,String title)
	{
		String host = "smtp.gmail.com";
	    String from = "mail.ICMgroup9";
	    String pass = "icm12345678";   
	    Properties props = System.getProperties();
	    props.put("mail.smtp.starttls.enable", "true");
	    props.put("mail.smtp.host", host);
	    props.put("mail.smtp.user", from);
	    props.put("mail.smtp.password", pass);
	    props.put("mail.smtp.port", "587");
	    props.put("mail.smtp.auth", "true");

	    String to = new String(Destination);

	    try{
		    Session session = Session.getDefaultInstance(props, null);
		    MimeMessage message = new MimeMessage(session);
		    message.setFrom(new InternetAddress(from));

		    InternetAddress[] toAddress = new InternetAddress[1];

		    // To get the array of addresses
		    //for( int i=0; i < 1; i++ ) { // changed from a while loop
		        toAddress[0] = new InternetAddress(to);
		    //}

		    //for( int i=0; i < toAddress.length; i++) { // changed from a while loop
		        message.addRecipient(Message.RecipientType.TO, toAddress[0]);
		    //}

		    message.setSubject(title);
		    message.setText(Msg);
		    Transport transport = session.getTransport("smtp");
		    transport.connect(host, from, pass);
		    transport.sendMessage(message, message.getAllRecipients());
		    transport.close();
	    }catch(AddressException e){
	    	//TODO handle this error
	    }catch(MessagingException e){
	    	e.printStackTrace();
	    }

	   }
}
